import wave

import pyaudio


def record_microphone(filename, duration=5, sample_rate=44100, channels=1, chunk=1024):
    """
    录制麦克风音频并保存为WAV文件
    :param filename: 输出文件名
    :param duration: 录制时长(秒)
    :param sample_rate: 采样率(Hz)
    :param channels: 声道数
    :param chunk: 缓冲区大小
    """
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=channels,
                    rate=sample_rate,
                    input=True,
                    frames_per_buffer=chunk)

    print("● 开始录音...")
    frames = []

    # 计算需要读取的帧数
    for _ in range(0, int(sample_rate / chunk * duration)):
        frames.append(stream.read(chunk))

    print("■ 录音完成")

    stream.stop_stream()
    stream.close()
    p.terminate()

    # 保存WAV文件
    with wave.open(filename, 'wb') as wf:
        wf.setnchannels(channels)
        wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
        wf.setframerate(sample_rate)
        wf.writeframes(b''.join(frames))

    print(f"✓ 文件已保存: {filename}")


if __name__ == "__main__":
    record_microphone("e:/test/mic_recording.wav", duration=10)
